package top.xxyu.shiro;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import top.xxyu.app.login.service.IUserService;
import top.xxyu.app.pojo.CurrentUser;
import top.xxyu.app.pojo.Module;
import top.xxyu.app.pojo.Role;
import top.xxyu.app.pojo.User;

/**
 * 类AuthRealm完成根据用户名去数据库的查询,并且将用户信息放入shiro中
 * 
 * @author xx
 *
 */
public class AuthRealm extends AuthorizingRealm {

	@Autowired
	private IUserService userService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection paramPrincipalCollection) {
		List<String> permissions=new ArrayList<>();
		//用户
		User user = (User) paramPrincipalCollection.fromRealm(this.getClass().getName()).iterator().next();
		//角色
		Set<Role> roles = user.getRoles();
		if (roles.size() > 0) {
			for (Role role : roles) {
				Set<Module> modules = role.getModules();
				//模块
				if (modules.size() > 0) {
					for (Module module : modules) {
						permissions.add(module.getMname());
					}
				}
			}
		}
		
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		//将权限放入shiro中
		simpleAuthorizationInfo.addStringPermissions(permissions);
		
		
		return simpleAuthorizationInfo;
	}

	/**
	 * 认证、登陆
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken paramAuthenticationToken)
			throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken) paramAuthenticationToken;
		String username = userToken.getUsername();
		User user = userService.findByUserNmae(username);
		CurrentUser currentUser = new CurrentUser(String.valueOf(user.getUid()),user.getUsername(),user.getPassword());
		SecurityUtils.getSubject().getSession().setAttribute(ShiroUtil.SESSION_CURRENT_USER, currentUser);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
		return info;
	}

}
